import store from '../store/index.js'
import persistentStorage from './storage.js'
const storage = persistentStorage()

// 设置基准地址
const BASEURL = 'https://huangjiangjun.top:3002/api/'

// 手动封装网络请求
function request({
	url,
	method = 'GET',
	header = {},
	data
}) {
	return new Promise((resolve, reject) => {
		const token = store.state.user.token.token || store.state.user.token
		if (token) header.token = token

		uni.request({
			url: `${BASEURL}${url}`,
			method: method,
			header,
			data,
			success(res) {
				if (res.statusCode === 401) {
					storage.setStorage('user', '')
					return uni.redirectTo({
						url: '/subpkg/login/login'
					})
				} else {
					resolve(res.data)
				}
			},
			fail(err) {
				reject(err)
				console.log(err)
			}
		})
	})
}

export default request